import subprocess as sp
from pathlib import Path as P

def convert(src_path, output_format='mp3', quality='high', output_dir=None):
    """黑魔法音频转换器：src_path=输入文件/目录, output_format=格式(mp3/m4a), quality=质量(high/medium/low/码率/source)"""
    # 魔法预设
    q_map = {
        'mp3': {'high': '-q:a 0', 'medium': '-q:a 2', 'low': '-q:a 6', 'source': 'source'},
        'm4a': {'high': '-b:a 256k', 'medium': '-b:a 192k', 'low': '-b:a 128k', 'source': 'source'}
    }
    
    # 寻找魔法材料
    src, out = P(src_path), P(output_dir) if output_dir else P(src_path).parent
    files = [src] if src.is_file() else [f for f in src.glob('*') if f.suffix[1:] in 'mp3 aac wma ogg wav flac ape alac mp4 avi mkv flv ts mov'.split()]
    
    for f in files:
        # 创建魔法容器
        dst = out/f"{f.stem}.{output_format}"
        while dst.exists(): dst = out/f"{f.stem}_{sum(1 for x in out.glob(f'{f.stem}*.{output_format}'))}.{output_format}"
        
        # 调制魔法药水
        q_val = q_map[output_format].get(quality, quality)
        br = sp.run(f'ffprobe -v error -select_streams a:0 -show_entries stream=bit_rate -of csv=p=0 "{f}"', 
                   shell=True, capture_output=True, text=True).stdout.strip() if 'source' in str(q_val) else None
        q_cmd = q_val if not br else f'-b:a {int(br)//1000}k' if br and br.isdigit() else q_map[output_format]['high']
        
        # 施放魔法
        sp.run(f'ffmpeg -i "{f}" -vn -y -loglevel error {q_cmd} "{dst}"', shell=True, check=True)
        print(f"✨ {f.name} → {dst.name} [⚡{quality}]")

if __name__ == "__main__":
    # 魔法参数配置 ,# 可选: mp3 或 m4a,# 可选: high/medium/low/数字码率(如'192k')/source
    input_file = r"F:\Documents\Music\0Output"
    output_format = "mp3"     
    quality_setting = "source"  
    output_directory = r""
    convert(input_file, output_format, quality_setting, output_directory)